package su.samlib.informer.utils.updaters.samizdatupdaters;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import su.samlib.informer.model.Author;
import su.samlib.informer.model.Book;
import su.samlib.informer.utils.updaters.AbstractBooksUpdater;

public class SamizdatApiBooksUpdater extends AbstractBooksUpdater {

    private static final String REQUEST_AUTHOR_TEXTS = "/cgi-bin/areader?q=razdel&order=date&object=";
    private static final int LINK = 0;
    private static final int AUTHOR_FIO = 1;
    private static final int TITLE = 2;
    private static final int FORM = 3;
    private static final int SIZE = 4;
    private static final int DATE_CHANGE = 5;
    private static final int VOTE_RESULT = 6;
    private static final int VOTE_COUNT = 7;
    private static final int DESCRIPTION = 8;
    final List<Book> list = new ArrayList<Book>();
    private Author author;
    
    @Override
    public void setAuthor(final Author a) {
        this.author = a;
    }

    @Override
    protected URL getRequestURL() {
        StringBuilder sb = new StringBuilder();
        URL result = null;
        try {
            final URL authorURL = new URL(getAuthorUrl(author));
            sb.append("http://");
            sb.append(authorURL.getHost());
            sb.append(REQUEST_AUTHOR_TEXTS);
            sb.append(authorURL.getPath());
            result = new URL(sb.toString());
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
    /**
     * Достает из URL страницу, чтоб получить URI произведения автора
     * @param url полный путь к произведению
     * @return URI произведения автора
     */
    private static String getPageFromUrlPath(String url) {
        final int lastSlash = url.lastIndexOf("/") + 1;
        return url.substring(lastSlash);
    }

    @Override
    public List<Book> getBooks() {
        final String str = getAuthorPage();
        
        int offset = 0;
        boolean endFlag = false;
        while (!endFlag) {
            Book tmpBook = new Book();
            for (int i = 0; i < 9; i++) {
                int firstPosition = str.indexOf("|", offset + 1);
                if (firstPosition == -1) {
                    endFlag = true;
                    break;
                }
                String tmpStr = str.substring(offset + 1, firstPosition);
                switch (i) {
                    case LINK:
                        tmpBook.setBookUri(getPageFromUrlPath(tmpStr + ".shtml"));
                        break;
                    case TITLE:
                        tmpBook.setBookTitle(unescapeAndCleanHtml(tmpStr.trim()));
                        break;
                    case DESCRIPTION:
                        tmpBook.setBookDescription(unescapeAndCleanHtml(tmpStr.trim()));
                        break;
                    case SIZE: {
                        int length = tmpStr.trim().length();
                        if (length != 0) {
                            tmpBook.setBookSize(new Integer(tmpStr));
                        } else {
                            tmpBook.setBookSize(0);
                        }
                        break;
                    }
                }
                offset = firstPosition;
            }
            if (!endFlag) {
                list.add(tmpBook);
            }
        }

        return list;
    }
}
